{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tokenizers import Tokenizer, models, trainers, pre_tokenizers\n",
    "\n",
    "# 创建 BPE Tokenizer\n",
    "tokenizer = Tokenizer(models.BPE())\n",
    "\n",
    "# 设置 Tokenizer 规则\n",
    "trainer = trainers.BpeTrainer(special_tokens=[\"<pad>\", \"<bos>\", \"<eos>\"], vocab_size=10000)\n",
    "tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()\n",
    "\n",
    "# 训练 Tokenizer\n",
    "file_paths = [\"data1.txt\", \"data2.txt\"]  # 你的训练数据集\n",
    "tokenizer.train(file_paths, trainer)\n",
    "\n",
    "# 保存 Tokenizer\n",
    "tokenizer.save(\"bpe_tokenizer.json\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "编码: ['he', 'll', 'o', 'w', 'or', 'ld', ',', 'ho', 'w', 'are', 'y', 'ou']\n",
      "解码: he ll o w or ld , ho w are y ou\n"
     ]
    }
   ],
   "source": [
    "from tokenizers import Tokenizer\n",
    "\n",
    "# 加载 BPE Tokenizer\n",
    "tokenizer = Tokenizer.from_file(\"bpe_tokenizer.json\")\n",
    "\n",
    "# 测试编码 & 解码\n",
    "text = \"hello world, how are you?\"\n",
    "encoded = tokenizer.encode(text)\n",
    "print(\"编码:\", encoded.tokens)\n",
    "print(\"解码:\", tokenizer.decode(encoded.ids))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
